﻿using System.Web.Http;
using DTcms.Web.Mvc.UI;
using System.Net;
using System.IO;
using System.Text;
using DTcms.Common;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DTcms.SMS;
using System.Web;
using System.Drawing.Imaging;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Drawing;

namespace DTcms.Web.Mvc.Controllers
{
    [ModelStateFilter]
    public class Submit_AjaxController : WebApiController
    {
        #region subimit方法移植
        #region 退出
        [HttpGet]
        public IHttpActionResult loginout()
        {
            //清险Session
            HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = null;

            //清除token
            Utils.WriteCookie(DTKeys.COOKIE_USER_TOKEN, "DTcms", -43200);
            //清除Cookies
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", -43200);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", -43200);
            Utils.WriteCookie("UserName", "DTcms", -1);
            Utils.WriteCookie("Password", "DTcms", -1);

            return Json(new { status = 1, msg = "退出成功！", url = _base.linkurl("index") });
        }
        #endregion
        #region 微信分享或配置
        [HttpGet]
        public IHttpActionResult weixinfx(string url)
        {
            StringBuilder strTxt = new StringBuilder();
            string jsapi_ticket = string.Empty; //jsapi_ticket
            string access_token = string.Empty; //access_token
            string signature = string.Empty; //signature

            //获得配置信息
            API.Weixin.Common.CRMComm wxComm = new API.Weixin.Common.CRMComm(); //获取AccessToKen类
            Model.weixin_account weixin_account = new BLL.weixin_account().GetModel(1);
            string timestamp = Senparc.Weixin.MP.Helpers.JSSDKHelper.GetTimestamp(); //生成签名的时间戳
            string nonceStr = Senparc.Weixin.MP.Helpers.JSSDKHelper.GetNoncestr(); //生成签名的随机串

            //如果Session为Null
            if (HttpContext.Current.Session["access_token"] != null || HttpContext.Current.Session["jsapi_ticket"] != null)
            {
                access_token = HttpContext.Current.Session["access_token"].ToString();
                jsapi_ticket = HttpContext.Current.Session["jsapi_ticket"].ToString();
                signature = wxComm.getSignature(jsapi_ticket, nonceStr, timestamp, url);
            }
            else
            {
                access_token = Utils.GetCookie("access_token", "WZHN");
                jsapi_ticket = Utils.GetCookie("jsapi_ticket", "WZHN");

                Dictionary<string, object> token = API.OAuth.weixin_helper.get_access_token(weixin_account.appid, weixin_account.appsecret);//获取access_token
                if (token == null || !token.ContainsKey("access_token"))
                {
                    return Json(new { islogin = 0, MSG = "" });
                }
                if (string.IsNullOrEmpty(access_token) || string.IsNullOrEmpty(jsapi_ticket))
                {
                    string error = string.Empty;
                    access_token = token["access_token"].ToString();
                    HttpContext.Current.Session["access_token"] = access_token;
                    jsapi_ticket = wxComm.GetJSAPI_Ticket(access_token);
                    HttpContext.Current.Session["jsapi_ticket"] = jsapi_ticket;

                    Utils.WriteCookie("access_token", "WZHN", access_token, 120);
                    Utils.WriteCookie("jsapi_ticket", "WZHN", jsapi_ticket, 120);
                }
                signature = wxComm.getSignature(jsapi_ticket, nonceStr, timestamp, url);
            }
            if (weixin_account != null)
            {
                return Json(new { islogin = 1, MSG = new { appid = weixin_account.appid, noncestr = nonceStr, signature = signature, timestamp = timestamp, url = url } });
            }
            else
            {
                return Json(new { islogin = 0, MSG = "" });
            }
        }
        #endregion
        #region 统计及输出
        #region 统计及输出阅读次数
        [HttpGet]
        public IHttpActionResult view_article_click(int channel_id, int click, int id)
        {
            if (channel_id == 0)
            {
                return Json(new { status = 0, msg = "对不起，频道参数传输有误！" });
            }
            int count = 0;
            if (id > 0)
            {
                BLL.article bll = new BLL.article();
                count = bll.GetClick(channel_id, id);
                if (click > 0)
                {
                    bll.UpdateField(channel_id, id, "click=click+1");
                }
            }
            return Json(new { status = 0, msg = count });
        }
        #endregion
        #region 输出商品价格
        [HttpGet]
        public IHttpActionResult view_article_price(string ids, int channel_id)
        {
            if (channel_id == 0 || string.IsNullOrEmpty(ids))
            {
                return Json(new { status = 0, msg = 0 });
            }
            int id = 0;
            string str_comment = string.Empty;
            string[] valItemArr = ids.Split(',');
            for (int i = 0; i < valItemArr.Length; i++)
            {
                id = Utils.StrToInt(valItemArr[i]);
                Model.article model = new BLL.article().GetModel(channel_id, id);
                if (model != null)
                {
                    str_comment = model.fields["sell_price"].ToString();
                }
                //是否加逗号
                if (i < valItemArr.Length - 1)
                {
                    str_comment += ",";
                }
            }
            return Json(new { status = 1, msg = str_comment });
        }
        #endregion
        #region 输出评论总数
        [HttpGet]
        public IHttpActionResult view_article_comment(string ids, int channel_id = 0)
        {
            if (channel_id == 0 || string.IsNullOrEmpty(ids))
            {
                return Json(new { status = 0, msg = 0 });
            }
            int count = 0, id = 0;
            List<ViewArticle> comment = new List<ViewArticle>();
            string[] valItemArr = ids.Split(',');
            for (int i = 0; i < valItemArr.Length; i++)
            {
                ViewArticle model = new ViewArticle();
                id = Utils.StrToInt(valItemArr[i]);
                count = Utils.StrToInt(new BLL.article_comment().GetCount("count(1)", "is_lock=0 and channel_id=" + channel_id + " and article_id=" + id));
                model.id = id;
                model.chrnum = count;
                comment.Add(model);
            }
            return Json(new { status = 1, msg = comment });
        }
        [HttpGet]
        public IHttpActionResult view_article_channel_comment(string ids, string chids)
        {
            if (string.IsNullOrEmpty(chids) || string.IsNullOrEmpty(ids))
            {
                return Json(new { status = 0, msg = 0 });
            }
            int count = 0, id = 0, channel_id = 0;
            List<ViewArticle> comment = new List<ViewArticle>();
            string[] valItemArr = ids.Split(',');
            string[] chArr = chids.Split(',');
            for (int i = 0; i < valItemArr.Length; i++)
            {
                ViewArticle model = new ViewArticle();
                id = Utils.StrToInt(valItemArr[i]);
                channel_id = Utils.StrToInt(chArr[i]);
                count = Utils.StrToInt(new BLL.article_comment().GetCount("count(1)", "is_lock=0 and channel_id=" + channel_id + " and article_id=" + id));
                model.id = id;
                model.chrnum = count;
                comment.Add(model);
            }
            return Json(new { status = 1, msg = comment });
        }
        #endregion
        #region 输出文章相册图片总数
        [HttpGet]
        public IHttpActionResult view_article_albums(string ids, int channel_id = 0)
        {
            if (channel_id == 0 || string.IsNullOrEmpty(ids))
            {
                return Json(new { status = 0, msg = 0 });
            }
            int count = 0, id = 0;
            List<ViewArticle> comment = new List<ViewArticle>();
            string[] valItemArr = ids.Split(',');
            for (int i = 0; i < valItemArr.Length; i++)
            {
                ViewArticle model = new ViewArticle();
                id = Utils.StrToInt(valItemArr[i]);
                count = Utils.StrToInt(new BLL.article_albums().GetCount("count(1)", "channel_id=" + channel_id + " and article_id=" + id));
                model.id = id;
                model.chrnum = count;
                comment.Add(model);
            }
            return Json(new { status = 1, msg = comment });
        }
        #endregion
        #region 输出附件下载总数
        [HttpGet]
        public IHttpActionResult view_attach_count(int channel_id, string ids, string view)
        {
            if (channel_id == 0 || string.IsNullOrEmpty(ids))
            {
                return Json(new { status = 0, msg = 0 });
            }
            int count = 0, id = 0;
            List<ViewArticle> comment = new List<ViewArticle>();
            string[] valItemArr = ids.Split(',');
            for (int i = 0; i < valItemArr.Length; i++)
            {
                ViewArticle model = new ViewArticle();
                id = Utils.StrToInt(valItemArr[i]);
                if (view.ToLower() == "count")
                {
                    count = new BLL.article_attach().GetCountNum(channel_id, id);
                }
                else
                {
                    count = new BLL.article_attach().GetDownNum(id);
                }
                model.id = id;
                model.chrnum = count;
                comment.Add(model);
            }
            return Json(new { status = 1, msg = comment });
        }
        #endregion
        public class ViewArticle
        {
            public int id;//文章ID
            public int chrnum;//点赞数 评论数
        }
        #endregion
        #region 验证邮箱是否可用
        [HttpPost]
        public IHttpActionResult validate_email(string param)
        {
            //如果为Null，退出
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "邮箱不可为空！" });
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == param.ToLower())
                {
                    return Json(new { status = "n", info = "该邮箱不可用！" });
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.ExistsEmail(param.Trim()))
            {
                return Json(new { status = "y", info = "该邮箱可用！" });
            }
            return Json(new { status = "n", info = "该邮箱已被注册！" });
        }
        #endregion
        #region 验证用户名是否可用
        [HttpPost]
        public IHttpActionResult validate_username(string param)
        {
            //如果为Null，退出
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "用户名不可为空！" });
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == param.ToLower())
                {
                    return Json(new { status = "n", info = "该用户名不可用！" });
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.Exists(param.Trim()))
            {
                return Json(new { status = "y", info = "该用户名可用！" });
            }
            return Json(new { status = "n", info = "该用户名已被注册！" });
        }
        #endregion
        #region 验证手机号是否可用
        [HttpPost]
        public IHttpActionResult validate_mobile(string param)
        {
            //如果为Null，退出
            if (string.IsNullOrEmpty(param))
            {
                return Json(new { status = "n", info = "手机号不可为空！" });
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == param.ToLower())
                {
                    return Json(new { status = "n", info = "该手机号不可用！" });
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.ExistsMobile(param.Trim()))
            {
                return Json(new { status = "y", info = "该手机号可用！" });
            }
            return Json(new { status = "n", info = "该手机号已被注册！" });
        }
        #endregion
        #region 用户登录
        [HttpPost]
        public IHttpActionResult user_login(int site_id, string txtUserName, string txtPassword, string chkRemember)
        {
            //检查站点目录
            string sitepath = new BLL.sites().GetBuildPath(site_id);
            if (string.IsNullOrEmpty(sitepath))
            {
                return Json(new { status = 0, msg = "站点传输参数不正确！" });
            }
            //检查用户名密码
            if (string.IsNullOrEmpty(txtUserName) || string.IsNullOrEmpty(txtPassword))
            {
                return Json(new { status = 0, msg = "请输入用户名或密码！" });
            }
            string login_session = string.Format("WebSite{0}LoginSun", site_id);
            if (HttpContext.Current.Session[login_session] == null)
            {
                HttpContext.Current.Session[login_session] = 1;
            }
            else
            {
                HttpContext.Current.Session[login_session] = Convert.ToInt32(HttpContext.Current.Session[login_session]) + 1;
            }
            //判断登录错误次数
            if (HttpContext.Current.Session[login_session] != null && Convert.ToInt32(HttpContext.Current.Session[login_session]) > 5)
            {
                return Json(new { status = 0, msg = "错误超过5次，关闭浏览器重新登录！" });
            }

            BLL.users bll = new BLL.users();
            Model.users model = bll.GetModel(txtUserName, txtPassword, userConfig.emaillogin, userConfig.mobilelogin, true);
            if (model == null)
            {
                return Json(new { status = 0, msg = "用户名或密码错误，请重试！" });
            }
            //检查用户是否通过验证
            if (model.status == 1) //待验证
            {
                if (userConfig.regverify == 1)
                {
                    return Json(new { status = 3, msg = "会员尚未通过验证！", url = _base.getlink(sitepath, _base.linkurl("register", "?action=sendmail&username=" + Utils.UrlEncode(model.user_name))) });
                }
                else
                {
                    return Json(new { status = 3, msg = "会员尚未通过验证！", url = _base.getlink(sitepath, _base.linkurl("register", "?action=sendsms&username=" + Utils.UrlEncode(model.user_name))) });
                }
            }
            else if (model.status == 2) //待审核
            {
                return Json(new { status = 3, msg = "会员尚未通过审核！", url = _base.getlink(sitepath, _base.linkurl("register", "?action=verify&username=" + Utils.UrlEncode(model.user_name))) });
            }
            //检查用户每天登录是否获得积分
            if (!new BLL.user_login_log().ExistsDay(model.user_name) && userConfig.pointloginnum > 0)
            {
                //new BLL.user_point_log().Add(model.id, model.user_name, userConfig.pointloginnum, "每天登录获得积分"); //增加用户登录积分
                //model = bll.GetModel(txtUserName, txtPassword, userConfig.emaillogin, userConfig.mobilelogin, true); //更新一下用户信息
            }
            HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
            HttpContext.Current.Session.Timeout = 45;
            //记住登录状态下次自动登录
            if (string.IsNullOrEmpty(chkRemember))
            {
                //防止Session提前过期
                Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
                Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
            }
            else if (chkRemember.ToLower() == "true")
            {
                Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name, 43200);
                Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password, 43200);
            }
            //写入登录日志
            new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
            //返回URL
            return Json(new { status = 1, msg = "会员登录成功！", uid = model.id, url = _base.linkurl("usercenter", "index") });
        }
        #endregion
        #region 检查用户是否登录
        [HttpGet]
        public IHttpActionResult user_check_login()
        {
            //检查用户是否登录
            if (userModel == null)
            {
                return Json(new { status = 0, username = "匿名用户！" });
            }
            return Json(new { status = 1, username = userModel.user_name });
        }
        #endregion
        #region 绑定第三方登录账户
        [HttpPost]
        public IHttpActionResult user_oauth_bind(string username, string password)
        {
            //检查URL参数
            if (HttpContext.Current.Session["oauth_name"] == null)
            {
                return Json(new { status = 0, msg = "错误提示：授权参数不正确！" });
            }
            //获取授权信息
            string result = Utils.UrlExecute(siteConfig.webpath + "api/oauth/result_json.aspx");
            if (result.Contains("error"))
            {
                return Json(new { status = 0, msg = "错误提示：请检查URL是否正确！" });
            }
            //反序列化JSON
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
            if (dic["ret"].ToString() != "0")
            {
                return Json(new { status = 0, msg = "错误代码：" + dic["ret"] + "，描述：" + dic["msg"] + "" });
            }

            //检查用户名密码
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Json(new { status = 0, msg = "温馨提示：请输入用户名或密码！" });
            }
            BLL.users bll = new BLL.users();
            Model.users model = bll.GetModel(username, password, userConfig.emaillogin, userConfig.mobilelogin, true);
            if (model == null)
            {
                return Json(new { status = 0, msg = "错误提示：用户名或密码错误！" });
            }
            //开始绑定
            Model.user_oauth oauthModel = new Model.user_oauth();
            oauthModel.oauth_name = dic["oauth_name"].ToString();
            oauthModel.user_id = model.id;
            oauthModel.user_name = model.user_name;
            oauthModel.oauth_access_token = dic["oauth_access_token"].ToString();
            oauthModel.oauth_openid = dic["oauth_openid"].ToString();
            int newId = new BLL.user_oauth().Add(oauthModel);
            if (newId < 1)
            {
                return Json(new { status = 0, msg = "错误提示：绑定过程中出错，请重新获取！" });
            }
            HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
            HttpContext.Current.Session.Timeout = 45;
            //记住登录状态，防止Session提前过期
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
            //写入登录日志
            new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
            //返回URL
            return Json(new { status = 1, msg = "会员登录成功！" });
        }
        #endregion
        #region 注册第三方登录账户
        [HttpPost]
        public IHttpActionResult user_oauth_register(string txtPassword, string txtEmail, string txtMobile, int site_id = 0)
        {
            //检查URL参数
            if (HttpContext.Current.Session["oauth_name"] == null)
            {
                return Json(new { status = 0, msg = "错误提示：授权参数不正确！" });
            }
            //获取授权信息
            string result = Utils.UrlExecute(siteConfig.webpath + "api/oauth/result_json.aspx");
            if (result.Contains("error"))
            {
                return Json(new { status = 0, msg = "错误提示：请检查URL是否正确！" });
            }
            //检查站点是否正确
            if (site_id == 0)
            {
                return Json(new { status = 0, msg = "对不起，站点传输参数有误！" });
            }
            string password = txtPassword.Trim();
            string email = Utils.ToHtml(txtEmail.Trim());
            string mobile = Utils.ToHtml(txtMobile.Trim());
            string userip = DTRequest.GetIP();
            //反序列化JSON
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
            if (dic["ret"].ToString() != "0")
            {
                return Json(new { status = 0, msg = "错误代码：" + dic["ret"] + "，" + dic["msg"] + "" });
            }
            BLL.users bll = new BLL.users();
            Model.users model = new Model.users();
            //如果开启手机登录要验证手机
            if (userConfig.mobilelogin == 1 && !string.IsNullOrEmpty(mobile))
            {
                if (bll.ExistsMobile(mobile))
                {
                    return Json(new { status = 0, msg = "对不起，该手机号码已被使用！" });
                }
            }
            //如果开启邮箱登录要验证邮箱
            if (userConfig.emaillogin == 1 && !string.IsNullOrEmpty(email))
            {
                if (bll.ExistsEmail(email))
                {
                    return Json(new { status = 0, msg = "对不起，该电子邮箱已被使用！" });
                }
            }
            //检查默认组别是否存在
            Model.user_groups modelGroup = new BLL.user_groups().GetDefault();
            if (modelGroup == null)
            {
                return Json(new { status = 0, msg = "用户尚未分组，请联系管理员！" });
            }
            //保存注册信息
            model.site_id = site_id;
            model.group_id = modelGroup.id;
            model.user_name = bll.GetRandomName(10); //随机用户名
            model.salt = Utils.GetCheckCode(6); //获得6位的salt加密字符串
            model.password = DESEncrypt.Encrypt(password, model.salt);
            model.email = email;
            model.mobile = mobile;
            if (!string.IsNullOrEmpty(dic["nick"].ToString()))
            {
                model.nick_name = dic["nick"].ToString();
            }
            if (dic["avatar"].ToString().StartsWith("http://"))
            {
                model.avatar = dic["avatar"].ToString();
            }
            if (!string.IsNullOrEmpty(dic["sex"].ToString()))
            {
                model.sex = dic["sex"].ToString();
            }
            if (!string.IsNullOrEmpty(dic["birthday"].ToString()))
            {
                model.birthday = Utils.StrToDateTime(dic["birthday"].ToString());
            }
            model.reg_ip = userip;
            model.reg_time = DateTime.Now;
            model.status = 0; //设置为正常状态
            model.id = bll.Add(model); //保存数据
            if (model.id < 1)
            {
                return Json(new { status = 0, msg = "注册失败，请联系网站管理员！" });
            }
            //赠送积分金额
            if (modelGroup.point > 0)
            {
                new BLL.user_point_log().Add(model.id, model.user_name, modelGroup.point, "注册赠送积分");
            }
            if (modelGroup.amount > 0)
            {
                new BLL.user_amount_log().Add(model.id, model.user_name, modelGroup.amount, "注册赠送金额");
            }
            //判断是否发送欢迎消息
            if (userConfig.regmsgstatus == 1) //站内短消息
            {
                new BLL.user_message().Add(1, "", model.user_name, "欢迎您成为本站会员", userConfig.regmsgtxt);
            }
            else if (userConfig.regmsgstatus == 2) //发送邮件
            {
                //取得邮件模板内容
                Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "welcomemsg" });
                if (mailModel != null)
                {
                    //替换标签
                    string mailTitle = mailModel.maill_title;
                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                    string mailContent = mailModel.content;
                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                    mailContent = mailContent.Replace("{username}", model.user_name);
                    //发送邮件
                    DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, model.email, mailTitle, mailContent);
                }
            }
            else if (userConfig.regmsgstatus == 3 && mobile != "") //发送短信
            {
                Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "welcomemsg" }); //取得短信内容
                if (smsModel != null)
                {
                    //替换标签
                    string msgContent = smsModel.content;
                    msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                    msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
                    msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
                    msgContent = msgContent.Replace("{username}", model.user_name);
                    //发送短信
                    string tipMsg = string.Empty;
                    SmsFactory.Sms().Send(model.mobile, smsModel.templateId, 2, msgContent, out tipMsg);
                }
            }
            //绑定到对应的授权类型
            Model.user_oauth oauthModel = new Model.user_oauth();
            oauthModel.oauth_name = dic["oauth_name"].ToString();
            oauthModel.user_id = model.id;
            oauthModel.user_name = model.user_name;
            oauthModel.oauth_access_token = dic["oauth_access_token"].ToString();
            oauthModel.oauth_openid = dic["oauth_openid"].ToString();
            new BLL.user_oauth().Add(oauthModel);

            HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
            HttpContext.Current.Session.Timeout = 45;
            //记住登录状态，防止Session提前过期
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
            //写入登录日志
            new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
            //返回URL
            return Json(new { status = 1, msg = "会员登录成功！" });
        }
        #endregion
        #region 用户注册
        [HttpPost]
        public IHttpActionResult user_register(int site_id, string txtCode, string imgcodeid, string codeindex, string txtUserName, string txtPassword, string txtEmail, string txtMobile)
        {
            string userip = DTRequest.GetIP();

            #region 验证各种参数信息
            //检查站点是否正确
            string sitepath = new BLL.sites().GetBuildPath(site_id); //站点目录
            if (site_id == 0 || string.IsNullOrEmpty(sitepath))
            {
                return Json(new { status = 0, msg = "对不起，站点传输参数有误！" });
            }
            //检查是否开启会员功能
            if (siteConfig.memberstatus == 0)
            {
                return Json(new { status = 0, msg = "对不起，会员功能已关闭，无法注册！" });
            }
            if (userConfig.regstatus == 0)
            {
                return Json(new { status = 0, msg = "对不起，系统暂不允许注册新用户！" });
            }
            //检查用户输入信息是否为空
            if (string.IsNullOrEmpty(txtUserName) || string.IsNullOrEmpty(txtPassword))
            {
                return Json(new { status = 0, msg = "对不起，用户名和密码不能为空！" });
            }
            //如果开启手机注册则要验证手机
            if (userConfig.regstatus == 2 && string.IsNullOrEmpty(txtMobile))
            {
                return Json(new { status = 0, msg = "错误：手机号码不能为空！" });
            }
            //如果开启邮箱注册则要验证邮箱
            if (userConfig.regstatus == 3 && string.IsNullOrEmpty(txtEmail))
            {
                return Json(new { status = 0, msg = "对不起，电子邮箱不能为空！" });
            }
            //检查用户名
            BLL.users bll = new BLL.users();
            if (bll.Exists(txtUserName))
            {
                return Json(new { status = 0, msg = "对不起，该用户名已经存在！" });
            }
            //如果开启手机登录要验证手机
            if (userConfig.mobilelogin == 1 && !string.IsNullOrEmpty(txtMobile))
            {
                if (bll.ExistsMobile(txtMobile))
                {
                    return Json(new { status = 0, msg = "对不起，该手机号码已被使用！" });
                }
            }
            //如果开启邮箱登录要验证邮箱
            if (userConfig.emaillogin == 1 && !string.IsNullOrEmpty(txtEmail))
            {
                if (bll.ExistsEmail(txtEmail))
                {
                    return Json(new { status = 0, msg = "对不起，该电子邮箱已被使用！" });
                }
            }
            //检查同一IP注册时隔
            if (userConfig.regctrl > 0)
            {
                if (bll.Exists(userip, userConfig.regctrl))
                {
                    return Json(new { status = 0, msg = "对不起，同IP在" + userConfig.regctrl + "小时内禁止重复注册！" });
                }
            }
            //检查默认组别是否存在
            Model.user_groups modelGroup = new BLL.user_groups().GetDefault();
            if (modelGroup == null)
            {
                return Json(new { status = 0, msg = "用户尚未分组，请联系网站管理员！" });
            }

            //检查验证码是否正确
            switch (userConfig.regstatus)
            {
                case 1: //验证网页验证码
                    string result1 = verify_code(imgcodeid, codeindex);
                    if (result1 != "success")
                    {
                        return Json(new { status = 0, msg = result1 });
                    }
                    break;
                case 2: //验证手机验证码
                    string result2 = verify_sms_code(txtCode);
                    if (result2 != "success")
                    {
                        return Json(new { status = 0, msg = result2 });
                    }
                    break;
                case 4: //验证邀请码
                    string result4 = verify_invite_reg(txtUserName, txtCode);
                    if (result4 != "success")
                    {
                        return Json(new { status = 0, msg = result4 });
                    }
                    break;
            }
            #endregion

            #region 保存用户注册信息
            Model.users model = new Model.users();
            model.site_id = site_id;
            model.group_id = modelGroup.id;
            model.user_name = txtUserName;
            model.nick_name = txtUserName;
            model.salt = Utils.GetCheckCode(6); //获得6位的salt加密字符串
            model.password = DESEncrypt.Encrypt(txtPassword, model.salt);
            model.email = txtEmail;
            model.mobile = txtMobile;
            model.reg_ip = userip;
            model.reg_time = DateTime.Now;
            //设置用户状态
            if (userConfig.regstatus == 3)
            {
                model.status = 1; //待验证
            }
            else if (userConfig.regverify == 1)
            {
                model.status = 2; //待审核
            }
            else
            {
                model.status = 0; //正常
            }
            //开始写入数据库
            model.id = bll.Add(model);
            if (model.id < 1)
            {
                return Json(new { status = 0, msg = "系统故障，请联系网站管理员！" });
            }
            //检查用户组是否需要赠送积分
            if (modelGroup.point > 0)
            {
                new BLL.user_point_log().Add(model.id, model.user_name, modelGroup.point, "注册赠送积分");
            }
            //检查用户组是否需要赠送金额
            if (modelGroup.amount > 0)
            {
                new BLL.user_amount_log().Add(model.id, model.user_name, modelGroup.amount, "注册赠送金额");
            }
            #endregion

            #region 是否发送欢迎消息
            if (userConfig.regmsgstatus == 1) //站内短消息
            {
                new BLL.user_message().Add(1, string.Empty, model.user_name, "欢迎您成为本站会员", userConfig.regmsgtxt);
            }
            else if (userConfig.regmsgstatus == 2 && !string.IsNullOrEmpty(txtEmail)) //发送邮件
            {
                //取得邮件模板内容
                Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "welcomemsg" });
                if (mailModel != null)
                {
                    //替换标签
                    string mailTitle = mailModel.maill_title;
                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                    string mailContent = mailModel.content;
                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                    mailContent = mailContent.Replace("{username}", model.user_name);
                    //发送邮件
                    DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, model.email, mailTitle, mailContent);
                }
            }
            else if (userConfig.regmsgstatus == 3 && !string.IsNullOrEmpty(txtMobile)) //发送短信
            {
                Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "welcomemsg" });//取得短信内容
                if (smsModel != null)
                {
                    //替换标签
                    string msgContent = smsModel.content;
                    msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                    msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
                    msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
                    msgContent = msgContent.Replace("{username}", model.user_name);
                    //发送短信
                    string tipMsg = string.Empty;
                    SmsFactory.Sms().Send(model.mobile, smsModel.templateId, 2, msgContent, out tipMsg);
                }
            }
            #endregion

            //需要Email验证
            if (userConfig.regstatus == 3)
            {
                string result2 = send_verify_email(sitepath, model); //发送验证邮件
                if (result2 != "success")
                {
                    return Json(new { status = 0, msg = result2 });
                }
                return Json(new { status = 1, msg = "注册成功，请进入邮箱验证激活账户！", url = _base.getlink(sitepath, _base.linkurl("register", "?action=sendmail&username=" + Utils.UrlEncode(model.user_name))) });
            }
            //需要人工审核
            else if (userConfig.regverify == 1)
            {
                return Json(new { status = 1, msg = "注册成功，请等待审核通过！", url = _base.getlink(sitepath, _base.linkurl("register", "?action=verify&username=" + Utils.UrlEncode(model.user_name))) });
            }
            else
            {
                HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
                HttpContext.Current.Session.Timeout = 45;
                //防止Session提前过期
                Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
                Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
                //写入登录日志
                new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
                return Json(new { status = 1, msg = "注册成功，欢迎成为本站会员！", url = _base.getlink(sitepath, _base.linkurl("usercenter", "index")) });
            }
        }
        #endregion
        #region 手机验证规则
        private static bool IsTelephone(string str_telephone)
        {
            return Regex.IsMatch(str_telephone, @"^1\d{10}$");
        }
        #endregion
        #region 获取发送手机短信令牌
        [HttpGet]
        public IHttpActionResult user_verify_token()
        {
            //判断是否在规定间隔内才能申请令牌
            if (HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN_TIME] != null)
            {
                //将时间值进行与当前时间对比,如超过有效期则分匹配令牌
                DateTime tokenTime = DateTime.Parse(HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN_TIME].ToString());
                TimeSpan ts = DateTime.Now - tokenTime;
                if (ts.Minutes < userConfig.regsmsexpired)
                {
                    return Json(new { status = 0, msg = "申请失败，请勿重复申请通讯令牌！" });
                }
            }
            //如未申请过或超过有效期则分配令牌
            string token = Utils.GetCheckCode(16);
            HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN] = token;
            HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN_TIME] = DateTime.Now;
            return Json(new { status = 1, msg = "成功申请通讯令牌！", token = token });
        }
        #endregion
        #region 发送手机短信验证码
        [HttpPost]
        public IHttpActionResult user_verify_smscode(string token, string mobile)
        {
            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                return Json(new { status = 0, msg = "发送失败，请填写手机号码！" });
            }
            if (!IsTelephone(mobile))
            {
                return Json(new { status = 0, msg = "手机格式错误！" });
            }
            //检查令牌是否有效
            if (HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN] != null && HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN].ToString() == token)
            {
                string result = send_verify_sms_code(mobile);
                if (result != "success")
                {
                    return Json(new { status = 0, msg = result });
                }
                //发送成功后作废令牌
                HttpContext.Current.Session[DTKeys.SESSION_SMS_TOKEN] = null;
                //通知成功
                return Json(new { status = 1, msg = "手机验证码发送成功！", time = userConfig.regsmsexpired });
            }
            //令牌无效返回失败信息
            return Json(new { status = 0, msg = "发送失败，" + userConfig.regsmsexpired + "分钟内请勿重复发送！" });
        }
        #endregion
        #region 发送注册验证邮件
        [HttpPost]
        public IHttpActionResult user_verify_email(int site_id, string username)
        {
            string sitepath = new BLL.sites().GetBuildPath(site_id); //当前站点目录

            if (site_id == 0 || string.IsNullOrEmpty(sitepath))
            {
                return Json(new { status = 0, msg = "网站传输参数有误！" });
            }
            if (string.IsNullOrEmpty(username))
            {
                return Json(new { status = 0, msg = "请检查用户名是否正确！" });
            }
            //检查邮件是否过快
            string cookie = Utils.GetCookie(DTKeys.COOKIE_USER_EMAIL);
            if (cookie == username)
            {
                return Json(new { status = 0, msg = "邮件发送间隔为二十分钟，请稍候再提交吧！" });
            }
            Model.users model = new BLL.users().GetModel(username);
            if (model == null)
            {
                return Json(new { status = 0, msg = "该用户不存在或已删除！" });
            }
            if (model.status != 1)
            {
                return Json(new { status = 0, msg = "该用户不需要邮箱验证！" });
            }
            string result = send_verify_email(sitepath, model);
            if (result != "success")
            {
                return Json(new { status = 0, msg = result });
            }
            Utils.WriteCookie(DTKeys.COOKIE_USER_EMAIL, username, 20); //20分钟内无重复发送
            return Json(new { status = 1, msg = "邮件已发送，请进入邮箱查看！" });
        }
        #endregion
        #region 用户取回密码
        [HttpPost]
        public IHttpActionResult user_getpassword(int site_id, string imgcodeid, string codeindex, string txtType, string txtUserName)
        {
            string sitepath = new BLL.sites().GetBuildPath(site_id);//站点目录
            //检查站点目录
            if (site_id == 0 || string.IsNullOrEmpty(sitepath))
            {
                return Json(new { status = 0, msg = "对不起，网站传输参数有误！" });
            }
            //检查用户名
            if (string.IsNullOrEmpty(txtUserName))
            {
                return Json(new { status = 0, msg = "对不起，用户名不可为空！" });
            }
            //检查取回密码类型
            if (string.IsNullOrEmpty(txtType))
            {
                return Json(new { status = 0, msg = "对不起，请选择取回密码类型！" });
            }
            //校检验证码
            string result = verify_code(imgcodeid, codeindex);
            if (result != "success")
            {
                return Json(new { status = 0, msg = result });
            }
            //检查用户信息
            BLL.users bll = new BLL.users();
            Model.users model = bll.GetNmaeModel(txtUserName);
            if (model == null)
            {
                return Json(new { status = 0, msg = "对不起，您输入的用户名不存在！" });
            }
            //发送取回密码的短信或邮件
            if (txtType.ToLower() == "mobile") //使用手机取回密码
            {
                #region 发送短信
                if (string.IsNullOrEmpty(model.mobile))
                {
                    return Json(new { status = 0, msg = "您尚未绑定手机号码，无法取回密码！" });
                }
                Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "usercode" }); //取得短信内容
                if (smsModel == null)
                {
                    return Json(new { status = 0, msg = "发送失败，短信模板不存在，请联系管理员！" });
                }
                string strcode = Utils.Number(4); //随机验证码
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(txtUserName, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddMinutes(userConfig.regsmsexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换标签
                string msgContent = smsModel.content;
                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
                msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
                msgContent = msgContent.Replace("{code}", codeModel.str_code);
                msgContent = msgContent.Replace("{valid}", userConfig.regsmsexpired.ToString());
                //发送短信
                string tipMsg = string.Empty;
                bool result1 = SmsFactory.Sms().Send(model.mobile, smsModel.templateId, 1, msgContent, out tipMsg);
                if (!result1)
                {
                    return Json(new { status = 0, msg = "发送失败，" + tipMsg + "" });
                }
                return Json(new { status = 1, msg = "手机验证码发送成功！", url = _base.getlink(sitepath, _base.linkurl("repassword", "?action=mobile&username=" + Utils.UrlEncode(model.user_name))) });
                #endregion
            }
            else if (txtType.ToLower() == "email") //使用邮箱取回密码
            {
                #region 发送邮件
                if (string.IsNullOrEmpty(model.email))
                {
                    return Json(new { status = 0, msg = "您尚未绑定邮箱，无法取回密码！" });
                }
                //生成随机码
                string strcode = Utils.GetCheckCode(20);
                //获得邮件内容
                Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "getpassword" });
                if (mailModel == null)
                {
                    return Json(new { status = 0, msg = "邮件发送失败，邮件模板内容不存在！" });
                }
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(txtUserName, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换模板内容
                string titletxt = mailModel.maill_title;
                string bodytxt = mailModel.content;
                titletxt = titletxt.Replace("{webname}", siteConfig.webname);
                titletxt = titletxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{webname}", siteConfig.webname);
                bodytxt = bodytxt.Replace("{weburl}", siteConfig.weburl);
                bodytxt = bodytxt.Replace("{webtel}", siteConfig.webtel);
                bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
                bodytxt = bodytxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{_base.linkurl}", "http://" + Request.RequestUri.Authority.ToLower() + _base.getlink(sitepath, _base.linkurl("repassword", "?action=email&code=" + codeModel.str_code)));
                //发送邮件
                try
                {
                    DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, model.email, titletxt, bodytxt);
                }
                catch
                {
                    return Json(new { status = 0, msg = "邮件发送失败，请联系本站管理员！" });
                }
                return Json(new { status = 1, msg = "邮件发送成功，请登录邮箱查看邮件！" });
                #endregion
            }
            return Json(new { status = 0, msg = "发生未知错误，请检查参数是否正确！" });
        }

        [HttpPost]
        public IHttpActionResult user_getpassword(int site_id, string imgcodeid, string codeindex, string chrname, string txtPassword, string txtPassword1, string code)
        {
            //检查验证字符串
            if (string.IsNullOrEmpty(code))
            {
                return Json(new { status = 0, msg = "校检码字符串不能为空！" });
            }
            //检查输入的新密码
            if (string.IsNullOrEmpty(txtPassword))
            {
                return Json(new { status = 0, msg = "请输入您的新密码！" });
            }
            if (txtPassword != txtPassword1)
            {
                return Json(new { status = 0, msg = "两次输入密码不一致！" });
            }
            //校检验证码
            string result = verify_code(imgcodeid, codeindex);
            if (result != "success")
            {
                return Json(new { status = 0, msg = result });
            }

            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(code);
            if (codeModel == null)
            {
                return Json(new { status = 0, msg = "校检码不存在或已过期！" });
            }
            //验证用户是否存在
            BLL.users userBll = new BLL.users();
            if (!userBll.Exists(codeModel.user_id))
            {
                return Json(new { status = 0, msg = "该用户不存在或已被删除！" });
            }
            Model.users userModel = userBll.GetModel(codeModel.user_id);
            //执行修改操作
            userModel.password = DESEncrypt.Encrypt(txtPassword, userModel.salt);
            userBll.Update(userModel);
            //更改验证字符串状态
            codeModel.count = 1;
            codeModel.status = 1;
            codeBll.Update(codeModel);
            return Json(new { status = 1, msg = "修改密码成功，请记住新密码！" });
        }
        #endregion
        #region 用户重设密码
        /// <summary>
        /// 用户重设密码
        /// </summary>
        /// <param name="hideCode">取回密码字符串</param>
        /// <param name="txtPassword">重设后的密码</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult user_repassword(int site_id, string hideCode, string txtPassword)
        {
            //检查验证字符串
            if (string.IsNullOrEmpty(hideCode))
            {
                return Json(new { status = 0, msg = "对不起，校检码字符串不能为空！" });
            }
            //检查输入的新密码
            if (string.IsNullOrEmpty(txtPassword))
            {
                return Json(new { status = 0, msg = "对不起，请输入您的新密码！" });
            }

            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(hideCode);
            if (codeModel == null)
            {
                return Json(new { status = 0, msg = "对不起，校检码不存在或已过期！" });
            }
            //验证用户是否存在
            BLL.users userBll = new BLL.users();
            if (!userBll.Exists(codeModel.user_id))
            {
                return Json(new { status = 0, msg = "对不起，该用户不存在或已被删除！" });
            }
            Model.users userModel = userBll.GetModel(codeModel.user_id);
            //执行修改操作
            userModel.password = DESEncrypt.Encrypt(txtPassword, userModel.salt);
            userBll.Update(userModel);
            //更改验证字符串状态
            codeModel.count = 1;
            codeModel.status = 1;
            codeBll.Update(codeModel);
            return Json(new { status = 1, msg = "修改密码成功，请记住新密码！" });
        }
        #endregion
        #endregion
        #region 通用外理方法
        #region 校检手机验证码
        private string verify_sms_code(string strcode)
        {
            if (string.IsNullOrEmpty(strcode))
            {
                return "对不起，请输入验证码！";
            }
            if (HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] == null)
            {
                return "对不起，验证码超时或已过期！";
            }
            if (strcode.ToLower() != (HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE].ToString()).ToLower())
            {
                return "您输入的验证码与系统的不一致！";
            }
            HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] = null;
            return "success";
        }
        #endregion
        #region 邀请注册处理方法
        private string verify_invite_reg(string user_name, string invite_code)
        {
            if (string.IsNullOrEmpty(invite_code))
            {
                return "邀请码不能为空！";
            }
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(invite_code);
            if (codeModel == null)
            {
                return "邀请码不正确或已过期！";
            }
            if (userConfig.invitecodecount > 0)
            {
                if (codeModel.count >= userConfig.invitecodecount)
                {
                    codeModel.status = 1;
                    return "该邀请码已经被使用！";
                }
            }
            //检查是否给邀请人增加积分
            if (userConfig.pointinvitenum > 0)
            {
                new BLL.user_point_log().Add(codeModel.user_id, codeModel.user_name, userConfig.pointinvitenum, "邀请用户【" + user_name + "】注册获得积分");
            }
            //更改邀请码状态
            codeModel.count += 1;
            codeBll.Update(codeModel);
            return "success";
        }
        #endregion
        #region 发送手机短信验证码
        private string send_verify_sms_code(string mobile)
        {
            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                return "发送失败，请填写手机号码！";
            }
            //检查是否过期
            string cookie = Utils.GetCookie(DTKeys.COOKIE_USER_MOBILE);
            if (cookie == mobile)
            {
                return "已发送短信，" + userConfig.regsmsexpired + "分钟后再试";
            }
            Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "usercode" }); //取得短信内容
            if (smsModel == null)
            {
                return "发送失败，短信模板不存在，请联系管理员！";
            }
            string strcode = Utils.Number(4); //随机验证码
            //替换标签
            string msgContent = smsModel.content;
            msgContent = msgContent.Replace("{webname}", siteConfig.webname);
            msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
            msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
            msgContent = msgContent.Replace("{code}", strcode);
            msgContent = msgContent.Replace("{valid}", userConfig.regsmsexpired.ToString());
            //发送短信
            string tipMsg = string.Empty;
            bool result = SmsFactory.Sms().Send(mobile, smsModel.templateId, 1, msgContent, out tipMsg);
            if (!result)
            {
                return "发送失败，" + tipMsg;
            }
            //写入SESSION，保存验证码
            HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] = strcode;
            Utils.WriteCookie(DTKeys.COOKIE_USER_MOBILE, mobile, userConfig.regsmsexpired); //规定时间内无重复发送
            return "success";
        }
        #endregion
        #region Email验证发送邮件
        private string send_verify_email(string site, Model.users userModel)
        {
            //生成随机码
            string strcode = Utils.GetCheckCode(20);
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel;
            //检查是否重复提交
            codeModel = codeBll.GetModel(userModel.user_name, DTEnums.CodeEnum.RegVerify.ToString(), "d");
            if (codeModel == null)
            {
                codeModel = new Model.user_code();
                codeModel.user_id = userModel.id;
                codeModel.user_name = userModel.user_name;
                codeModel.type = DTEnums.CodeEnum.RegVerify.ToString();
                codeModel.str_code = strcode;
                codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                codeModel.add_time = DateTime.Now;
                new BLL.user_code().Add(codeModel);
            }
            //获得邮件内容
            Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "regverify" });
            if (mailModel == null)
            {
                return "邮件发送失败，邮件模板内容不存在！";
            }
            //替换模板内容
            string titletxt = mailModel.maill_title;
            string bodytxt = mailModel.content;
            titletxt = titletxt.Replace("{webname}", siteConfig.webname);
            titletxt = titletxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{webname}", siteConfig.webname);
            bodytxt = bodytxt.Replace("{webtel}", siteConfig.webtel);
            bodytxt = bodytxt.Replace("{weburl}", siteConfig.weburl);
            bodytxt = bodytxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
            bodytxt = bodytxt.Replace("{_base.linkurl}", "http://" + Request.RequestUri.Authority.ToLower() + _base.getlink(site, _base.linkurl("register", "?action=checkmail&code=" + codeModel.str_code)));
            //发送邮件
            try
            {
                DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, userModel.email, titletxt, bodytxt);
            }
            catch
            {
                return "邮件发送失败，请联系本站管理员！";
            }
            return "success";
        }
        #endregion
        #region 生成二维码图片
        [HttpGet]
        public HttpResponseMessage QRImage(string url, int width = 133, int height = 133)
        {
            MediaTypeHeaderValue _mediaType = MediaTypeHeaderValue.Parse("image/jpg");//指定文件类型
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                url = HttpContext.Current.Request.Url.Authority.ToLower() + url;
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                Bitmap img = BarcodeHelper.Generate1(url, width, height);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, ImageFormat.Jpeg);
                ms.Dispose();

                response.Content = new ByteArrayContent(ms.ToArray());
                response.Content.Headers.ContentType = _mediaType;
                return response;
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }
        #endregion
        #region 找回密码 判断是否发送邮箱/手机
        public IHttpActionResult sendFind(string chrname, string imgcodeid, string codeindex)
        {
            if (string.IsNullOrEmpty(chrname))
            {
                return Json(new { islogin = 0, error = "请输入您账户的邮箱地址/手机号码！" });
            }
            //校检验证码
            string result = verify_code(imgcodeid, codeindex);
            if (result != "success")
            {
                return Json(new { status = 0, error = result });
            }
            Model.users model = new BLL.users().GetNmaeModel(chrname);
            if (model == null)
            {
                return Json(new { islogin = 0, error = "输入的邮箱/手机未找到用户！" });
            }
            if (Utils.HasEmail(chrname))
            {
                #region 发送邮件
                if (string.IsNullOrEmpty(model.email))
                {
                    return Json(new { status = 0, msg = "您尚未绑定邮箱，无法取回密码！" });
                }
                //生成随机码
                string strcode = Utils.GetCheckCode(20);
                //获得邮件内容
                Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "getpassword" });
                if (mailModel == null)
                {
                    return Json(new { status = 0, msg = "邮件发送失败，邮件模板内容不存在！" });
                }
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(model.user_name, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换模板内容
                string titletxt = mailModel.maill_title;
                string bodytxt = mailModel.content;
                titletxt = titletxt.Replace("{webname}", siteConfig.webname);
                titletxt = titletxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{webname}", siteConfig.webname);
                bodytxt = bodytxt.Replace("{weburl}", siteConfig.weburl);
                bodytxt = bodytxt.Replace("{webtel}", siteConfig.webtel);
                bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
                bodytxt = bodytxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{code}", codeModel.str_code);
                //发送邮件
                try
                {
                    DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, model.email, titletxt, bodytxt);
                }
                catch
                {
                    return Json(new { islogin = 0, error = "邮件发送失败，请联系本站管理员！" });
                }
                return Json(new { islogin = 1, msg = "邮件发送成功，请登录邮箱查看邮件！" });
                #endregion
            }
            else if (IsTelephone(chrname))
            {
                #region 发送短信
                Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "usercode" }); //取得短信内容
                if (smsModel == null)
                {
                    return Json(new { islogin = 0, msg = "发送失败，短信模板不存在，请联系管理员！" });
                }
                string strcode = Utils.Number(4); //随机验证码
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(model.user_name, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddMinutes(userConfig.regsmsexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换标签
                string msgContent = smsModel.content;
                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
                msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
                msgContent = msgContent.Replace("{code}", codeModel.str_code);
                msgContent = msgContent.Replace("{valid}", userConfig.regsmsexpired.ToString());
                //发送短信
                string tipMsg = string.Empty;
                bool result1 = SmsFactory.Sms().Send(chrname, smsModel.templateId, 1, msgContent, out tipMsg);
                if (!result1)
                {
                    return Json(new { islogin = 0, error = "发送失败，" + tipMsg + "" });
                }
                return Json(new { islogin = 1, msg = "手机验证码发送成功！" });
                #endregion
            }
            return Json(new { islogin = 0, error = "输入邮箱/手机格式错误！" });
        }
        #endregion
        #endregion END通用方法
        #region 验证码
        //原来的方法
        [HttpGet]
        public IHttpActionResult verifyCode(string w = "", int width = 80, int height = 22)
        {
            int fontSize = 16 + (width - 80) / 5;
            if (w == "m")
            {
                width = 100;
                height = 35;
                fontSize = 24;
            }
            string chkCode = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session
            HttpContext.Current.Session[DTKeys.SESSION_CODE] = chkCode;
            //创建画布
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 1; i++)
            {
                int x1 = rnd.Next(width);
                int y1 = rnd.Next(height);
                int x2 = rnd.Next(width);
                int y2 = rnd.Next(height);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, (float)0);
            }
            //画噪点 
            for (int i = 0; i < 100; i++)
            {
                int x = rnd.Next(bmp.Width);
                int y = rnd.Next(bmp.Height);
                Color clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                //保存图片数据  
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);

                //输出图片流
                Stream stream = new MemoryStream(ms.ToArray());
                httpResponseMessage.Content = new StreamContent(stream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
            }
            finally
            {
                //显式释放资源 
                bmp.Dispose();
                g.Dispose();
            }
            return ResponseMessage(httpResponseMessage);
        }

        /// <summary>
        /// 统一生成验证码
        /// </summary>
        /// <param name="codeindex">正确的第几位</param>
        /// <returns></returns>
        private string getCode(out string codeStr, out int codeindex)
        {
            string chkCode = string.Empty;
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            Random code = new Random();
            codeindex = rnd.Next(10);
            codeStr = string.Empty;
            //生成验证码字符串 
            for (int i = 0; i < 10; i++)
            {
                char ch = character[rnd.Next(character.Length)];
                chkCode += ch;
                if (i == codeindex)
                {
                    codeStr += ch;
                }
            }
            return chkCode;
        }

        //生成验证码
        [HttpGet]
        public IHttpActionResult codeimg(string id, int width = 240, int height = 50)
        {
            int fontSize = 35;
            string chkCode = string.Empty;
            Random rnd = new Random();
            string SESSION_CODE = HttpContext.Current.Session[DTKeys.SESSION_CODE].ToString();
            chkCode = Utils.SplitString(SESSION_CODE, ",")[0];

            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };

            //创建画布
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 1; i++)
            {
                int x1 = rnd.Next(width);
                int y1 = rnd.Next(height);
                int x2 = rnd.Next(width);
                int y2 = rnd.Next(height);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 22, (float)0);
            }
            //画噪点 
            for (int i = 0; i < 100; i++)
            {
                int x = rnd.Next(bmp.Width);
                int y = rnd.Next(bmp.Height);
                Color clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                //保存图片数据  
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);

                //输出图片流
                Stream stream = new MemoryStream(ms.ToArray());
                httpResponseMessage.Content = new StreamContent(stream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
            }
            finally
            {
                //显式释放资源 
                bmp.Dispose();
                g.Dispose();
            }
            return ResponseMessage(httpResponseMessage);
        }

        //生成保存验证码
        [HttpGet]
        public IHttpActionResult getcodeimg(int islogin = 1)
        {
            string codeStr = string.Empty, imgcodeid = StringHelper.CreateIDCode();
            int codeindex = 0;
            string chkCode = getCode(out codeStr, out codeindex);
            string SESSION_CODE = chkCode + "," + codeStr + "," + codeindex + "," + imgcodeid;
            HttpContext.Current.Session[DTKeys.SESSION_CODE] = SESSION_CODE;
            return Json(new { islogin = islogin, MSG = new { code = codeStr, codeDate = DateTime.Now, imgcodeid = imgcodeid } });
        }

        //判断验证码
        [HttpGet]
        public IHttpActionResult iscodeimg(string jsonxml)
        {
            if (string.IsNullOrEmpty(jsonxml))
            {
                return Json(new { islogin = 0, error = "参数错误！" });
            }
            string codeindex = JsonHelper.GetString(jsonxml, "codeindex");
            string imgcodeid = JsonHelper.GetString(jsonxml, "imgcodeid");
            if (string.IsNullOrEmpty(codeindex) || string.IsNullOrEmpty(imgcodeid))
            {
                return Json(new { islogin = 0, error = "JSON数据错误！" });
            }

            //校检验证码
            string result = verify_code(imgcodeid, codeindex, false);
            if (result == "success")
            {
                return Json(new { islogin = 1, success = true, MSG = "" });
            }
            #region 重新生成验证码
            return getcodeimg(0);
            #endregion
        }
        #endregion
        #region 文件下载
        [HttpGet]
        public HttpResponseMessage Download(string site, int id)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            HttpResponseMessage moved = new HttpResponseMessage(HttpStatusCode.Moved);
            if (string.IsNullOrEmpty(site))
            {
                moved.Headers.Location = new Uri(HttpUrl("站点传输参数不正确！"));
                return moved;
            }
            //获得下载ID
            if (id < 1)
            {
                moved.Headers.Location = new Uri(HttpUrl("文件参数传值不正确！"));
                return moved;
            }
            //检查下载记录是否存在
            BLL.article_attach bll = new BLL.article_attach();
            if (bll.Get(id) == null)
            {
                moved.Headers.Location = new Uri(HttpUrl("您要下载的文件不存在或已经被删除！"));
                return moved;
            }
            Model.article_attach model = bll.Get(id);
            //检查积分是否足够
            if (model.point > 0)
            {
                //检查用户是否登录
                if (userModel == null)
                {
                    //自动跳转URL
                    moved.Headers.Location = new Uri(HttpUrl("该资源文件需要登录！"));
                    return moved;
                }
                //如果该用户未曾下载过该附件
                if (!bll.ExistsLog(model.id, userModel.id))
                {
                    //检查积分
                    if (model.point > userModel.point)
                    {
                        moved.Headers.Location = new Uri(HttpUrl("您的积分不足支付本次下载！"));
                        return moved;
                    }
                    //扣取积分
                    int result = new BLL.user_point_log().Add(userModel.id, userModel.user_name, model.point * -1, "下载附件：“" + model.file_name + "”，扣减积分");
                    //添加下载记录
                    if (result > 0)
                    {
                        bll.AddLog(userModel.id, userModel.user_name, model.id, model.file_name);
                    }
                }
            }
            //下载次数+1
            bll.UpdateFile("id=" + id, "down_num=down_num+1");

            //检查文件本地还是远程
            if (model.file_path.ToLower().StartsWith("http://"))
            {
                FileStream stream = new FileStream(model.file_path, FileMode.Open);
                response.Content = new StreamContent(stream);
                return response;
            }
            else
            {
                //取得文件物理路径
                string fullFileName = Utils.GetMapPath(model.file_path);
                if (!File.Exists(fullFileName))
                {
                    moved.Headers.Location = new Uri(HttpUrl("您要下载的文件不存在或已经被删除！"));
                    return moved;
                }
                FileStream stream = new FileStream(fullFileName, FileMode.Open);
                response.Content = new StreamContent(stream);
                Encoding encoding = System.Text.Encoding.Default;
                HttpContext.Current.Response.ContentEncoding = encoding;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = HttpUtility.UrlEncode(model.file_name)
                };
                return response;
            }
        }
        private string HttpUrl(string msg)
        {
            string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority.ToLower();
            if (string.IsNullOrEmpty(msg))
            {
                return url + _base.linkurl("error");
            }
            else
            {
                return url + _base.linkurl("error", "?msg=" + Utils.UrlEncode(msg));
            }
        }
        #endregion
        #region 评论新方法
        #region 评论回复（主用与发布的人回复）=====获取
        [HttpPost]
        public IHttpActionResult getrevertrep(int id, int channel_id, int styleid = 0, int isadmin = 1, int tplid = 1)
        {
            if (id == 0)
            {
                return Json(new { status = 0, msg = "参数出现错误！" });
            }

            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = new Model.article_comment();
            model = bll.GetModel(id);
            if (model == null)
            {
                return Json(new { status = 0, msg = "评论不存在或已删除！" });
            }
            if (channel_id == 0)
            {
                return Json(new { status = 0, msg = "参数出现错误！" });
            }
            //检查该文章是否存在
            Model.article artModel = new BLL.article().GetModel(model.channel_id, model.article_id);
            if (artModel == null)
            {
                return Json(new { status = 0, msg = "主题不存在或已删除！" });
            }
            return Json(new { status = 1, msg = "<div class=\"comment_source\"><div class=\"comment_user\"><span class=\"userName\">" + model.user_name + "</span> 的评论  " + model.add_time + "</div><p class=\"comment_content\">" + Utils.ToTxt(model.content) + "<textarea style=\"display:none\" id=\"replay_tips_input\">" + Utils.ToTxt(model.content) + "</textarea></p></div><div class=\"comment_replay_list display0\"></div><div class=\"write_2014\" id=\"write_replay\"><div class=\"timer clearfix\"><p class=\"timer display0\" style=\"float:right; font-size:12px; color:#666;\">回复日期：</p>回复：</div><textarea id=\"replay_tips_textarea\" class=\"textarea\"></textarea><button class=\"sys_btn_blue\" onclick=\"return post_replay();\" type=\"button\">确认提交</button></div>" });
        }
        #endregion

        #region 评论回复（主用与发布的人回复）=====提交
        /// <summary>
        /// 评论回复（主用与发布的人回复）
        /// </summary>
        /// <param name="Chrmark">原回复内容</param>
        /// <param name="replaycontent">现在人的回复</param>
        /// <param name="id">主ID</param>
        /// <param name="styleid"></param>
        /// <param name="shopid">该评论的商家ID</param>
        /// <param name="isadmin">是否登录</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult saverevert_rep(string Chrmark, string replaycontent, int id = 0, int styleid = 0, int shopid = 0, int isadmin = 1)
        {
            if (userModel == null)
            {
                return Json(new { islogin = 0, error = "需要登录！" });
            }
            if (id == 0 || string.IsNullOrEmpty(Chrmark))
            {
                return Json(new { islogin = 0, error = "传输传递有误！" });
            }
            if (string.IsNullOrEmpty(replaycontent))
            {
                return Json(new { islogin = 0, error = "回复内容未填写！" });
            }
            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = bll.GetModel(id);
            if (model == null)
            {
                return Json(new { islogin = 0, error = "评论不存在！" });
            }
            model.is_reply = 1;
            model.reply_content = replaycontent;
            model.reply_time = DateTime.Now;
            model.is_lock = 0;

            if (bll.Update(model))
            {
                return Json(new { islogin = 1, error = "回复成功！" });
            }
            return Json(new { islogin = 0, error = "更新失败！" });
        }
        #endregion

        #region 获取评论列表
        public string CommentReply = "<div class=\"comment_reply\">{5}<div class=\"comment_user clearfix\"><span class=\"comment_floor right\">{0}楼</span><span class=\"userName\">{1}</span> 的评论  {2}</div><p class=\"comment_content\">{3}</p><div class=\"comment_vote_show\"><div class=\"comment_vote\"><a href=\"#\" onclick=\"return loadRevertReplay(this,'{4}');\" class=\"replay_btn replay_life\"></a></div></div></div>";
        public string PCCommentEmpty = "<div style=\"font-size:18px; text-align:center; padding:100px 0;\" id=\"listEmpty\">抱歉，暂时还没有人发表评论哦~！</div>";
        public string WapCommentEmpty = "<div style=\"font-size: 16px; text-align: center; padding: 30px 0px 40px;\" id=\"listEmpty\"><img src=\"/template/wap/main/default/images/x11_nofind_list.png\" style=\"display: block; width: 180px; margin: 20px auto;\"><p style=\"color:#aaa; font-size:14px;\">暂无任何评论</p></div>";
        public string pageNavigation()
        {
            if (Utils.IsMobile())
            {
                return "";
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 获取评论列表
        /// </summary>
        /// <param name="jsoncallback"></param>
        /// <param name="id">文章ID</param>
        /// <param name="styleid">评论类型</param>
        /// <param name="channel_id">频道ID</param>
        /// <param name="shopid">商家ID</param>
        /// <param name="tplid">？</param>
        /// <param name="PageNo">页码</param>
        /// <param name="score">0:全部 1:好评 2:中评 3:差评</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult getrevert(int id = 0, int styleid = 0, int channel_id = 0, int shopid = 0, int tplid = 1, int PageNo = 1, int score = 0)
        {
            int pageSize = 10, articleuserId = 0;
            string strwhere = string.Empty, ids = string.Empty, isbuy = string.Empty, author = string.Empty, avatar = string.Empty;

            if (id == 0 || channel_id == 0)
            {
                return Json(new { islogin = 1, p = 1, PageCount = PageNo, RecCount = 0, PageSplit = "<em class=\"firstpage\"><span class=\"prev\"><</span></em><em class=\"endpage\"><span class=\"next\">></span></em>", MSG = "<div id=\"total_revert\" data-num=\"0\"><div style=\"font-size:18px;text-align:center;padding:100px 0\" id=\"listEmpty\">没有找到符合条件的信息~！</div><div class=\"pageNavigation\"><em class=\"firstpage\"><span class=\"prev\"><</span></em> <em class=\"endpage\"><span class=\"next\">></span></em></div></div><input type=\"hidden\" id=\"isuserpinglun\" value=\"1\">" });
            }
            strwhere = string.Format("is_lock=0 and channel_id={0} and article_id={1} and styleid={2}", channel_id, id, styleid);
            //if (channel_id == 2)//判断这个频道是否是下载频道
            //{
            //    List<Model.article_attach> list = new BLL.article_attach().GetModelList(0, string.Format("channel_id={0} and article_id={1}", channel_id, id), "id", "add_time desc");
            //    string[] rows = list.Select(t => t.id.ToString()).ToArray();
            //    ids = string.Join(",", rows);
            //    articleuserId = Utils.StrToInt(new BLL.article().GetField(channel_id, "user_id", "id=" + id));
            //}
            if (userModel != null && userModel.avatar != "")
            {
                avatar = userModel.avatar;
            }

            BLL.article_comment bll = new BLL.article_comment();
            var resultlist = bll.GetQueryPage(PageNo, pageSize, strwhere, "add_time desc");
            List<Model.article_comment> ds = resultlist.Items;
            totalcount = Utils.ObjToInt(resultlist.TotalItems);
            int PageCount = (totalcount + pageSize - 1) / pageSize;

            string PageSplit = string.Empty, MSG = string.Empty; ;
            if (ds.Count > 0)
            {
                PageSplit = string.Format("<div class=\"pageNavigation\">{0}</div><input type=\"hidden\" id=\"isuserpinglun\" value=\"{1}\" />", Utils.RevertPageList(pageSize, PageNo, totalcount, 8), PageNo);

                MSG = "<div id=\"total_revert\" data-num=\"" + totalcount + "\">";
                int number = 0;

                foreach (var item in ds)
                {
                    #region 计算楼层数
                    int row_number = 1;
                    if (PageNo == 1)
                    {
                        row_number = totalcount - number;
                    }
                    else
                    {
                        row_number = totalcount - number - pageSize;
                    }
                    #endregion
                    if (string.IsNullOrEmpty(avatar) && item.qq != "")
                    {
                        avatar = string.Format("https://q.qlogo.cn/headimg_dl?dst_uin={0}&spec=100", item.qq);
                    }
                    else if (string.IsNullOrEmpty(avatar))
                    {
                        avatar = "/images/avatar_45.png";
                    }

                    #region 频道
                    //if (ids != "")
                    //{
                    //    bool buy = Utils.StrToInt(new BLL.user_attach_log().GetCount("count(1)", string.Format("user_id={0} and attach_id in({1})", item.user_id, ids))) > 0;
                    //    if (buy)
                    //    {
                    //        isbuy = "<span class=\"layui-badge-rim layui-btn-disabled\" style=\"margin-left:5px;color:#FF5722\">已购买</span>";
                    //    }
                    //    if (articleuserId == item.user_id && item.user_id > 0)
                    //    {
                    //        author = "<span class=\"layui-badge-rim layui-btn-disabled\" style=\"margin-left:5px;color:#FFB800\">作者</span>";
                    //    }
                    //}
                    MSG += "<div class=\"comment_item\">";
                    MSG += string.Format("<div class=\"comment_face\"><img src=\"{0}\" alt=\"\"></div>", avatar);
                    MSG += "<div class=\"comment_box\">";
                    MSG += string.Format("<div class=\"comment_user clearfix\"><span class=\"right\">{0}楼</span><span class=\"userName\">{1} <span class=\"userName_s\">{2}</span>{3}{4}</span></div>", row_number, item.user_name, item.add_time.ToString("MM-dd HH:mm:ss"), isbuy, author);

                    #region 获取该条评论下的回复内容
                    if (item.parent_id != 0)
                    {
                        int row_reply = 0;
                        string[] Strsplit = item.class_list.Replace("," + item.id, "").Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        string Reply = string.Empty;
                        List<Model.article_comment> list = bll.GetModelList(0, string.Format("id in({0})", string.Join(",", Strsplit)), "*", "id desc,add_time desc");

                        foreach (var modelt in list)
                        {
                            row_reply++;
                            int comment_floor = list.Count - row_reply + 1;//楼层
                            string comment_content = Utils.ToTxt(modelt.content);//评论内容中的HTML进行处理
                            string comment_time = modelt.add_time.ToString("MM-dd HH:mm:ss");//评论时间处理

                            if (row_reply == list.Count && list.Count != 1)
                            {
                                Reply = string.Format(Reply, comment_floor, modelt.user_name, comment_time, comment_content, modelt.id, "");
                            }
                            else
                            {
                                Reply = string.Format(row_reply == 1 ? CommentReply : Reply, comment_floor, modelt.user_name, comment_time, comment_content, modelt.id, list.Count == 1 ? "" : CommentReply);
                            }
                        }
                        MSG += Reply;
                    }
                    #endregion

                    MSG += string.Format("<p class=\"comment_content\">{0}</p>", Utils.ToTxt(item.content));
                    MSG += string.Format("<div class=\"comment_vote\"><a href=\"#\" onclick=\"return edit_replay(this,'{0}','0');\" class=\"edit_btn display0\">回评</a>", item.id);
                    MSG += string.Format("<a href=\"#\" onclick=\"return loadDelQuick(this,'{0}');\" class=\"edit_btn display0\">更多</a>", item.id);
                    MSG += string.Format("<a href=\"#\" onclick=\"return loadRevertReplay(this,'{0}','0');\" class=\"replay_btn replay_life\"></a>", item.id);
                    MSG += string.Format("<a href=\"#\" onclick=\"return putRevertPage(this,'{0}','xianhua=1');\" class=\"zan_btn\"><em class=\"num\">{1}</em></a>", item.id, item.xianhua);
                    MSG += string.Format("<!--<a href=\"#\" onclick=\"return putRevertPage(this,'{0}','isyes=1');\">支持(<em class=\"num\">0</em>)</a>,<a href=\"#\" onclick=\"return putRevertPage(this,'{0}','isyes=2');\">反对(<em class=\"num\">0</em>)</a>-->", item.id);
                    MSG += string.Format("<!--<span class=\"display0\">管理回复:0<br></span><p color=\"blue\"  class=\"display1\">网友回复:</p><div class=\"comment_reply\"><div class=\"comment_user clearfix\"><span class=\"comment_floor right\">1楼</span><span class=\"userName\">wenxin</span> 的评论  08-26 11:31</div><p class=\"comment_content\">OMG~全方位展示，不出家门环游世界的节奏~</p><div class=\"comment_vote_show\"><div class=\"comment_vote\"><a href=\"#\" onclick=\"return loadRevertReplay(this,'2570');\" class=\"replay_btn replay_life\"></a></div></div></div>-->");
                    MSG += string.Format("</div></div><p class=\"manage_replay display{0}\" data-isrep=\"{0}\">{1}回复：{2}　<span class=\"time\">{3}</span></p></div>", item.is_reply, "管理", item.reply_content, item.reply_time);
                    #endregion

                    number++;
                }

                MSG += string.Format("{1}</div>{0}", PageSplit, styleid == 1 ? "</ul>" : "");
            }
            else
            {
                PageSplit = "<em class=\"firstpage\"><span class=\"prev\"><</span></em><em class=\"endpage\"><span class=\"next\">></span></em>";
                MSG = "<div id=\"total_revert\" data-num=\"0\">" + (Utils.IsMobile() ? WapCommentEmpty : PCCommentEmpty) + "<div class=\"pageNavigation\"><em class=\"firstpage\"><span class=\"prev\"><</span></em> <em class=\"endpage\"><span class=\"next\">></span></em></div></div><input type=\"hidden\" id=\"isuserpinglun\" value=\"1\">";
            }
            return Json(new { islogin = 1, p = PageNo, PageCount = PageCount, RecCount = totalcount, PageSplit = PageSplit, MSG = MSG });
        }

        //删除评论
        [HttpPost]
        public IHttpActionResult delrevert(string checkId)
        {
            if (string.IsNullOrEmpty(checkId))
            {
                return Json(new { status = 0, msg = "删除失败，请检查传输参数！" });
            }

            BLL.article_comment bll = new BLL.article_comment();
            int sucCount = 0;
            int errorCount = 0;
            int id;
            string[] arrId = checkId.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                if (int.TryParse(arrId[i], out id))
                {
                    if (bll.Delete(id, userModel.id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion

        #region 提交评论
        /// <summary>
        /// 提交评论
        /// </summary>
        /// <param name="chrmark">评论内容</param>
        /// <param name="id">文章ID</param>
        /// <param name="styleid">评论类型</param>
        /// <param name="channel_id">频道ID</param>
        /// <param name="shopid">商家ID</param>
        /// <param name="tplid"></param>
        /// <param name="isrep">表示是否是属于回复</param>
        /// <param name="istg"></param>
        /// <param name="Parentid">回复评论ID</param>
        /// <param name="score">星级 1:好评  2:中评  3:差评</param>
        /// <param name="score1">星级 1 2 3 4 5星</param>
        /// <param name="score2">星级</param>
        /// <param name="score3">星级</param>
        /// <param name="u_mail">您的邮箱</param>
        /// <param name="u_qq">您的QQ</param>
        /// <param name="u_name">您的称呼</param>
        /// <param name="u_url">您的网站</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult saverevert(string chrmark, string u_mail, string u_qq, string u_name, string u_url, int is_email = 0, int id = 0, int styleid = 0, int channel_id = 0, int shopid = 0, int tplid = 0, int isrep = 0, int istg = 0, int Parentid = 0, int score = 1, int score1 = 0, int score2 = 0, int score3 = 0)
        {
            #region 参数获取及验证
            if (userConfig.iscomment == 1 && userModel == null)
            {
                return Json(new { islogin = 0, isopen = 1, error = "必须登录后才能评论！" });
            }
            if (id == 0 || channel_id == 0)
            {
                return Json(new { islogin = 0, isopen = 1, error = "对不起，参数传递错误！" });
            }
            if (!string.IsNullOrEmpty(u_mail) && !Utils.IsEmail(u_mail))
            {
                return Json(new { islogin = 0, isopen = 1, error = "邮箱格式错误！" });
            }
            if (!string.IsNullOrEmpty(u_url) && !Utils.IsUrl(u_url))
            {
                return Json(new { islogin = 0, isopen = 1, error = "网址格式错误！" });
            }
            if (string.IsNullOrEmpty(u_name))
            {
                return Json(new { islogin = 0, isopen = 1, error = "你的称呼是必须的！" });
            }
            if (string.IsNullOrEmpty(chrmark))
            {
                return Json(new { islogin = 0, isopen = 1, error = "请输入评论内容！" });
            }

            int site_id = 0;
            int article_id = 0;
            if (styleid == 0)
            {
                //检查该文章是否存在
                Model.article artModel = new BLL.article().GetModel(channel_id, id);
                if (artModel == null)
                {
                    return Json(new { islogin = 0, isopen = 1, error = "主题不存在或已删除！" });
                }
                site_id = artModel.site_id;
                channel_id = artModel.channel_id;
                article_id = artModel.id;
            }

            #endregion
            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = new Model.article_comment();

            //检查用户是否登录
            int user_id = 0;
            string user_name = "游客";
            if (userModel != null)
            {
                user_id = userModel.id;
                u_mail = userModel.email;
                user_name = userModel.nick_name;
            }

            model.site_id = site_id;
            model.channel_id = channel_id;
            model.article_id = article_id;
            model.content = Utils.ToHtml(chrmark);
            model.user_id = user_id;
            model.user_name = user_name;
            model.user_ip = DTRequest.GetIP();
            model.is_lock = siteConfig.commentstatus; //审核开关
            model.add_time = DateTime.Now;
            model.system = DTRequest.GetPhoneType();
            model.city = DTRequest.GetCity();
            model.is_reply = 0;
            model.class_layer = 0;
            model.parent_id = Parentid;

            model.score1 = score1;
            model.xianhua = 0;
            model.score = score;

            model.qq = u_qq;
            model.email = u_mail;
            model.web = u_url;
            model.is_email = is_email;
            model.browser = DTRequest.GetBrowser();
            if (bll.Add(model) > 0)
            {
                if (model.is_lock == 1)//开启了审核
                {
                    return Json(new { islogin = 1, isopen = 0 });
                }
                else
                {
                    return Json(new { islogin = 1, isopen = 1, MSG = chrmark });
                }
            }
            return Json(new { islogin = 0, isopen = 1, error = "对不起，保存过程中发生错误！" });
        }
        #endregion

        #region 评论点赞
        [HttpGet]
        public IHttpActionResult setrevert(int id = 0, int styleid = 0, int channel_id = 0)
        {
            if (id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = bll.GetModel(id);
            if (model == null)
            {
                return Json(new { status = 0, msg = "评论不存在！" });
            }
            bll.UpdateFile("id=" + id, "xianhua=xianhua+1");
            return Json(new { status = 1, msg = "点赞成功！" });
        }
        #endregion

        #region 分享参数
        [HttpGet]
        public IHttpActionResult GetTemplate(string pageShareStyle)
        {
            return Json(new { Id = "detail_news", Title = "文章详情页", Summary = "文章详情页的摘要", ImagePath = "", Module = 10, Key = 20 });
        }
        #endregion

        #region 评论图片base64图片上传
        /// <summary>
        /// 评论图片base64图片上传
        /// </summary>
        /// <param name="table_id"></param>
        /// <param name="id"></param>
        /// <param name="dir"></param>
        /// <param name="state"></param>
        /// <param name="filewidth"></param>
        /// <param name="fileheight"></param>
        /// <param name="smallfilewidth1"></param>
        /// <param name="smallfileheight1"></param>
        /// <param name="Base64">是否是base64</param>
        /// <param name="Base64Filename">上传文件名</param>
        /// <param name="imgFile">base64数据</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult kindeditor(string table_id, int id, string dir, string state, int filewidth, int fileheight, int smallfilewidth1, int smallfileheight1, int Base64, string Base64Filename, string imgFile)
        {
            string url = string.Empty, thumb = string.Empty;
            if (userModel == null)
            {
                return Json(new { error = 1, message = "请登录后上传！" });
            }
            //检查参数
            if (imgFile.Length == 0)
            {
                return Json(new { error = 1, message = "请先上传一张图片！" });
            }
            Model.article_albums model = new Model.article_albums();
            BLL.article_albums bll = new BLL.article_albums();
            //取得保存的新文件名
            UpLoad upFiles = new UpLoad();
            bool result = upFiles.base64Image(imgFile, out url);
            if (!result)
            {
                return Json(new { error = 1, message = "上传过程中发生意外错误！" });
            }
            //生成缩略图
            upFiles.base64Thumb(imgFile, Base64Filename, out thumb);
            model.add_time = DateTime.Now;
            model.original_path = url;
            model.thumb_path = thumb;
            model.remark = Base64Filename;
            model.article_id = 0;
            model.channel_id = 0;
            int albid = bll.Add(model);
            return Json(new { error = 0, smallurl = thumb, url = url, id = albid });
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ThirdId">评论关联业务Id</param>
        /// <param name="PageSize">每页条数</param>
        /// <param name="Keywords">关键字</param>
        /// <param name="PageID">分页页数</param>
        /// <param name="CommentType">评论分类</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetFrontCommentPages(int ThirdId, int PageSize, string Keywords, int PageID, int CommentType, int channel_id)
        {
            BLL.article_comment bll = new BLL.article_comment();
            string strwhere = string.Format("is_lock=0 and channel_id={0} and article_id={1}", channel_id, ThirdId);
            var resultlist = bll.GetQueryPage(PageID, PageSize, strwhere, "add_time desc");
            //int PageCount = (totalcount + PageSize - 1) / PageSize;

            Paged<CommentSimpleDto> pageFristComments = new Paged<CommentSimpleDto>();
            Paged<CommentCommonDto> paged = new Paged<CommentCommonDto>();
            if (resultlist.TotalItems > 0)
            {
                //pageFristComments.Data = resultlist.Items;
                pageFristComments.TotalPage = resultlist.TotalPages;
                pageFristComments.TotalRecord = resultlist.TotalItems;
            }
            return Json(new { Data = resultlist.Items, TotalPage = resultlist.TotalPages, TotalRecord = totalcount });
        }

        public class CommentSimpleDto
        {
            /// <summary>
            ///  主键
            /// </summary>
            public int Id
            {
                get;
                set;
            }

            /// <summary>
            ///  评论关联业务Id
            /// </summary>
            public int ThirdId
            {
                get;
                set;
            }

            /// <summary>
            /// 被回复的评论的id，如果为0，表示一级评论
            /// </summary>
            public int ParentId
            {
                get;
                set;
            }

            /// <summary>
            /// 频道id
            /// </summary>
            public int ChannelId
            {
                get;
                set;
            }

            /// <summary>
            ///  审核状态
            /// </summary>
            public int IsKill
            {
                get;
                set;
            }

            /// <summary>
            ///  回复内容
            /// </summary>
            public string Content
            {
                get;
                set;
            }

            /// <summary>
            ///  评论标题，用于关键字查询
            /// </summary>
            public string ThirdTitle
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户id
            /// </summary>
            public int UserId
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户名称
            /// </summary>
            public string UserName
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户头像
            /// </summary>
            public string UserHeadFile
            {
                get;
                set;
            }

            /// <summary>
            ///  发布时间
            /// </summary>
            public DateTime CreateTime
            {
                get;
                set;
            }

            /// <summary>
            ///  Ip地址
            /// </summary>
            public string Ip
            {
                get;
                set;
            }

            /// <summary>
            /// 预留 是否后台评论回复
            /// </summary>
            public bool IsAdminComment
            {
                get;
                set;
            }

            /// <summary>
            /// 是否特殊评论，（即需在业务表插入评分的评论）
            /// </summary>
            public bool IsSpecial
            {
                get;
                set;
            }

            /// <summary>
            /// 点赞数
            /// </summary>
            public int Likes
            {
                get;
                set;
            }
        }
        public class CommentCommonDto
        {
            /// <summary>
            ///  主键
            /// </summary>
            public int Id
            {
                get;
                set;
            }

            /// <summary>
            ///  评论标题，用于关键字查询
            /// </summary>
            public string ThirdTitle
            {
                get;
                set;
            }

            /// <summary>
            ///  评论关联业务Id
            /// </summary>
            public int ThirdId
            {
                get;
                set;
            }

            /// <summary>
            /// 被回复的评论的id，如果为0，表示一级评论
            /// </summary>
            public int ParentId
            {
                get;
                set;
            }

            /// <summary>
            /// 频道ID
            /// </summary>
            public int ChannelId
            {
                get;
                set;
            }

            /// <summary>
            ///  审核状态
            /// </summary>
            public int IsKill
            {
                get;
                set;
            }

            /// <summary>
            ///  回复内容
            /// </summary>
            public string Content
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户id
            /// </summary>
            public int UserId
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户名称
            /// </summary>
            public string UserName
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户头像
            /// </summary>
            public string UserHeadFile
            {
                get;
                set;
            }

            /// <summary>
            ///  发布时间
            /// </summary>
            public DateTime CreateTime
            {
                get;
                set;
            }

            /// <summary>
            /// 二级评论
            /// </summary>
            public IEnumerable<CommentSecondCommonDto> SecondCommentDtos
            {
                get;
                set;
            }

            /// <summary>
            ///  Ip地址
            /// </summary>
            public string Ip
            {
                get;
                set;
            }

            /// <summary>
            /// 预留 是否后台评论回复
            /// </summary>
            public bool IsAdminComment
            {
                get;
                set;
            }

            /// <summary>
            /// 是否特殊评论，（即需在业务表插入评分的评论）
            /// </summary>
            public bool IsSpecial
            {
                get;
                set;
            }

            /// <summary>
            /// 点赞数
            /// </summary>
            public int Likes
            {
                get;
                set;
            }

            public CommentCommonDto()
            {
                SecondCommentDtos = new List<CommentSecondCommonDto>();
            }
        }
        public class CommentSecondCommonDto
        {
            /// <summary>
            ///  主键
            /// </summary>
            public int Id
            {
                get;
                set;
            }

            /// <summary>
            ///  评论关联业务Id
            /// </summary>
            public int ThirdId
            {
                get;
                set;
            }

            /// <summary>
            ///  评论标题，用于关键字查询
            /// </summary>
            public string ThirdTitle
            {
                get;
                set;
            }

            /// <summary>
            /// 被回复的评论的id，如果为0，表示一级评论
            /// </summary>
            public int ParentId
            {
                get;
                set;
            }

            /// <summary>
            /// 频道ID
            /// </summary>
            public int ChannelId
            {
                get;
                set;
            }

            /// <summary>
            ///  审核状态
            /// </summary>
            public int IsKill
            {
                get;
                set;
            }

            /// <summary>
            ///  回复内容
            /// </summary>
            public string Content
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户id
            /// </summary>
            public int UserId
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户名称
            /// </summary>
            public string UserName
            {
                get;
                set;
            }

            /// <summary>
            ///  评论用户头像
            /// </summary>
            public string UserHeadFile
            {
                get;
                set;
            }

            /// <summary>
            ///  发布时间
            /// </summary>
            public DateTime CreateTime
            {
                get;
                set;
            }

            /// <summary>
            /// 是否后台评论回复
            /// </summary>
            public bool IsAdminComment
            {
                get;
                set;
            }
        }
        public class Paged<T>
        {
            /// <summary>
            /// 对象列表
            /// </summary>
            public IEnumerable<T> Data
            {
                get;
                set;
            } = new List<T>();

            /// <summary>
            /// 总记录数
            /// </summary>
            public long TotalRecord
            {
                get;
                set;
            }

            /// <summary>
            /// 总页数
            /// </summary>
            public long TotalPage
            {
                get;
                set;
            }

            /// <summary>
            /// 分页模型
            /// </summary>
            /// <typeparam name="T"></typeparam>
            public Paged()
            {

            }

            public Paged(IEnumerable<T> data = null, int totalRecord = 0, int totalPage = 0)
            {
                if (data != null)
                {
                    Data = data;
                }
                TotalRecord = totalRecord;
                TotalPage = totalPage;
            }

            /// <summary>
            /// 便捷设置全部数据
            /// </summary>
            /// <param name="totalRecord"></param>
            /// <param name="pageSize"></param>
            public void SetTotalPage(int totalRecord, int pageSize)
            {
                TotalRecord = totalRecord;
                TotalPage = ((totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1));
            }

            /// <summary>
            /// 计算分页范围
            /// </summary>
            /// <param name="pageSize">每页数量</param>
            /// <param name="pageNumber">页码</param>
            /// <returns></returns>
            public Tuple<int, int> MinAndMax(int pageSize, int pageNumber)
            {
                if (pageNumber > 0 && pageSize > 0)
                {
                    return new Tuple<int, int>(pageSize * (pageNumber - 1), pageSize * pageNumber + 1);
                }
                return new Tuple<int, int>(1, 100);
            }
        }
        #endregion
    }
}